package com.wyb.service.impl;

import com.wyb.mapper.UserMapper;
import com.wyb.pojo.LoginUser;
import com.wyb.constant.Result;
import com.wyb.pojo.User;
import com.wyb.service.LoginService;
import com.wyb.utils.JwtUtil;
import com.wyb.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;
    @Override
    /*
     * @description:自定义登录实现
     * @author: ruge
     * @date: 2023/3/6 14:10
     * @param: [user]User类
     * @return: com.wyb.pojo.ResponseResult
     */
    public Result login(User user) {

        UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断结果是否为空
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:"+userId, loginUser);
        //把token响应给前端
        Map<String,Object> map = new HashMap<>();
        map.put("token", jwt);


        return new Result(200, "登陆成功",map);
    }

    @Override
    /*
     * @description:自定义注销
     * @author: ruge
     * @date: 2023/3/6 14:12
     * @param: []
     * @return: com.wyb.pojo.ResponseResult
     */
    public Result logout() {

        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String userId = loginUser.getUser().getId().toString();

        redisCache.deleteObject("login:"+userId);
        return new Result(200, "注销成功" );
    }

    @Override
    /*
     * @description:
     * @author: ruge
     * @date: 2023/3/6 14:13
     * @param: [jwt]根据token获取用户信息
     * @return: com.wyb.pojo.ResponseResult
     */
    public Result getUser(String jwt) {

        String userId="";
        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //返回用户信息
//        User user = userMapper.selectById(Integer.parseInt(userId));
//        Map<String, Object> map = ObjToMap.objectToMap(user);
        LoginUser loginUser = redisCache.getCacheObject("login:" + userId);


        return new Result(200, "成功查询用户信息", loginUser.getUser());
    }
}
